package com.itbz.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 基于Druid连接池获取数据库连接工具类
 */
public class JdbcDruidUtil {
    //数据库连接池对象
    private static DataSource dataSource;
    static {
        try {
            //获取读取配置文件的字节输入流对象
            InputStream is = JdbcDruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            //创建Properties对象
            Properties pro=new Properties();
            //加载文件
            pro.load(is);
            //创建连接池
            dataSource = DruidDataSourceFactory.createDataSource(pro);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取数据库连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
    //关闭连接对象
    public static void closeConnection(Connection connection){
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //事务回滚
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭Statement对象
    public static void closeStatement(Statement statement){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭ResultSet
    public static void closeResultSet(ResultSet resultSet){
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭资DML操作时关闭资源
    public static void  closeResource(Statement statement,Connection connection){
        //先关闭Statement对象
        closeStatement(statement);
        //再关闭Connection对象
        closeConnection(connection);
    }
    //查询时关闭资源
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //先关闭ResultSet对象
        closeResultSet(resultSet);
        //再关闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}